﻿/*  
	------------------------------------------------------------------------
	 NQ Core Library
	
	 Homepage: http://www.awzhome.de/
	------------------------------------------------------------------------
	
	This Source Code Form is subject to the terms of the Mozilla Public
	License, v. 2.0. If a copy of the MPL was not distributed with this
	file, You can obtain one at http://mozilla.org/MPL/2.0/.
   
	The Original Code is code of NQ Core Library.

	The Initial Developer of the Original Code is Andreas Weizel.
	Portions created by the Initial Developer are
	Copyright (C) 2012 Andreas Weizel. All Rights Reserved.
	
	Contributor(s): (none)
	
	------------------------------------------------------------------------
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AWZhome.NQ.Core.Utility
{
	/// <summary>
	/// Helper class used to cache log messages and suspend notification
	/// about them to a later point.
	/// </summary>
	internal class LogMessageCache
	{
		private class LogMessage
		{
			public DateTime Timestamp;
			public object SourceService;
			public NQLogType LogType;
			public string Message;
		}

		private Queue<LogMessage> _messageCache = new Queue<LogMessage>();

		/// <summary>
		/// Caches a log message.
		/// </summary>
		/// <param name="sourceService">Instance of the service that has initiated the log event.</param>
		/// <param name="logType">Type of the logged message.</param>
		/// <param name="logMessage">Message text.</param>
		public void CacheMessage(DateTime timestamp, object sourceService, NQLogType logType, string logMessage)
		{
			_messageCache.Enqueue(new LogMessage()
			{
				Timestamp = timestamp,
				SourceService = sourceService,
				LogType = logType,
				Message = logMessage
			});
		}

		/// <summary>
		/// Fires notification events for all cached log messages and clears the queue.
		/// </summary>
		public void DissolveCache()
		{
			while (_messageCache.Count > 0)
			{
				LogMessage cachedMessage = _messageCache.Dequeue();
				NQServiceManagerImpl serviceManager = NQServiceManager.Instance as NQServiceManagerImpl;
				if (serviceManager != null)
				{
					// Fire event through InvokeSyncMethod() method of ServiceManager to be thread-safe.
					serviceManager.InvokeSyncMethod<NQLogEventArgs, bool>(serviceManager.OnMessageLogged,
						new NQLogEventArgs(cachedMessage.Timestamp, cachedMessage.SourceService, cachedMessage.LogType, cachedMessage.Message));
				}
			}
		}
	}
}
